import 'dart:io';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pages/PadView.dart';
import 'package:word_range_client/pages/PhoneView.dart';
import 'package:word_range_client/pages/WindowsView.dart';
import 'package:word_range_client/pages/general/RegisterView.dart';
import 'package:word_range_client/viewModels/UserViewModel.dart';
import 'package:word_range_client/widgets/general/MsgDialog.dart';
import 'package:word_range_client/widgets/general/Toastification.dart';

import '../../pojo/Result.dart';

class LoginView extends StatelessWidget {
  const LoginView({super.key, this.phone = "", this.password = ""});
  
  final String phone;
  final String password;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("登录"),
      ),
      body: _LoginViewBody(phone: phone,password: password,)
    );
  }
}


class _LoginViewBody extends StatefulWidget {
  const _LoginViewBody({super.key, required this.phone, required this.password});

  final String phone;
  final String password;

  @override
  State<_LoginViewBody> createState() => _LoginViewBodyState();
}

class _LoginViewBodyState extends State<_LoginViewBody> {

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();


  @override
  void initState(){
    super.initState();
    _phoneController.text = widget.phone;
    _passwordController.text = widget.password;
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _passwordController.dispose();
    super.dispose();
  }


  Future<void> login() async {
    UserViewModel userViewModel = UserViewModel();
    String phone = _phoneController.text;
    String password = _passwordController.text;
    Toastification toastification = Toastification(context: context);
    try {
      Result result = await userViewModel.login(phone, password);
      if(result.code != 1){
        String msg = result.msg!;
        toastification.showError(msg);
        return;
      }
      toastification.showSuccess("欢迎您！");
      toHomePage();
    } catch (e) {
      print(e);
    }
  }

  Future<void> toHomePage() async {
    final prefs = await SharedPreferences.getInstance();
    final isDarkMode = prefs.getBool('isDarkMode') ?? false;

    if(Platform.isAndroid){
      final bool isMobileLayout = MediaQuery.of(context).size.width < 600;
      if(isMobileLayout){
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => PhoneView(isDarkMode: isDarkMode)));
      }else{
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => PadView(isDarkMode: isDarkMode)));
      }
    }else{   // 目前只支持安卓、Windows
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => WindowsView(isDarkMode: isDarkMode)));
    }
  }

  Future<void> showHelpDialog() async {
    MsgDialog dialog = MsgDialog(context);
    bool? confirm = await dialog.showAlertDialog(
        "遇到问题？", "账户是您注册时填写的手机号。若您遗忘了您的密码，可以点击下方按钮找回",
        "找回密码", "关闭");
    if(confirm == true){
      toRetrievePage();
    }
  }

  void toRetrievePage(){
    print("跳转至找回密码页面");
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 900),
          child: ListView(
            children: [
              const SizedBox(height: 20,),
              const Text("账号密码登录",style: TextStyle(fontSize: 35,fontWeight: FontWeight.w600),),
              const SizedBox(height: 40,),
              TextField(
                controller: _phoneController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: "账户",
                  hintText: "请输入您注册时的手机号",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.people),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              const SizedBox(height: 12,),
              TextField(
                obscureText: true,
                controller: _passwordController,
                keyboardType: TextInputType.visiblePassword,
                decoration: const InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  hintStyle: TextStyle(color: Colors.grey),
                  prefixIcon: Icon(Icons.key),
                  enabledBorder: UnderlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20,),
              Hero(
                  tag: "ApplyButton",
                  child: _LoginButton(login: login,)
              ),
              const SizedBox(height: 10,),
              const _RegisterButton(),
              const SizedBox(height: 5,),
              TextButton(
                  onPressed: showHelpDialog,
                  child: const Text("我遇到了问题")
              ),
            ],
          ),
        ),
      ),
    );
  }
}



class _LoginButton extends StatelessWidget {
  const _LoginButton({super.key, required this.login,});

  final Function login;

  // 这里有个坑, 你不能直接使用父组件传过来的方法，不然会直接调用
  void _login(){
    login();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      height: 55,
      child: ElevatedButton(
        onPressed: _login,
        style: ButtonStyle(
          shape: MaterialStateProperty.all(
              RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15)
              )
          ),
          backgroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.primary),
          foregroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.background),
          overlayColor: MaterialStateProperty.all(Theme.of(context).colorScheme.onPrimary),
        ),
        child: const Text("登录",style: TextStyle(fontSize: 20),),
      ),
    );
  }
}


class _RegisterButton extends StatefulWidget {
  const _RegisterButton({super.key});

  @override
  State<_RegisterButton> createState() => _RegisterButtonState();
}

class _RegisterButtonState extends State<_RegisterButton> {

  void toRegisterPage(){
    Navigator.of(context).push(MaterialPageRoute(builder: (context) => const RegisterView()));
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      height: 55,
      child: ElevatedButton(
        onPressed: toRegisterPage,
        style: ButtonStyle(
          shape: MaterialStateProperty.all(
              RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15)
              )
          ),
        ),
        child: const Text("还没有账号?立即注册",style: TextStyle(fontSize: 17),),
      ),
    );
  }
}



